#include "softkey.h"
#include "ui_softkey.h"
#include<QDebug>
#include<QPixmap>
#include<QPalette>
softKey::softKey(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::softKey)
{


    ui->setupUi(this);
    this->postion=0;
    QFile file("./pinyin.txt");
    file.open(QIODevice::ReadOnly);

        QString strLine;
        QStringList list;
        while(!file.atEnd())
        {
            strLine= file.readLine();
            strLine.remove("\n").remove("\t").remove(" ");
            list=strLine.split("=");
            this->strList[list.at(0)]=list.at(1);
        }

    file.close();

       this->cnBT[0]=ui->cn1;
       this->cnBT[1]=ui->cn2;
       this->cnBT[2]=ui->cn3;
       this->cnBT[3]=ui->cn4;
       this->cnBT[4]=ui->cn5;
       this->cnBT[5]=ui->cn6;
        for(int i=0;i<6;i++)
        {
            QObject::connect(cnBT[i],SIGNAL(clicked(bool)),this,SLOT(which_cn()));
        }

}

softKey::~softKey()
{
    delete ui;
}

void softKey::reset_btStyle()
{
    for(int i=0;i<6;i++)
    {
        this->cnBT[i]->setStyleSheet("");
    }
}

void softKey::paintEvent(QPaintEvent *event)
{
    QPixmap pix;
    pix.load(":/new/prefix1/image/UI5.png");

     QPainter painter(this);
     painter.drawPixmap(0,0,800,300,pix);
}

void softKey::on_prevBt_clicked()
{
    this->postion-=6;
    if(postion<0)
    {
        this->postion=0;
    }
    int j=1;
    for(int i=postion;i<postion+6&&i<cnList.count();i++)
    {
        cnBT[j-1]->setText(QString("%1.%2").arg(j).arg(cnList.at(i)));
        j++;
    }
}

void softKey::on_nextBt_clicked()
{
    this->postion+=6;
    if(postion+6 >cnList.count())
    {
        this->postion-=6;
        return;
    }
    int j=1;
    for(int i=postion;i<postion+6&&i<cnList.count();i++)
    {
        cnBT[j-1]->setText(QString("%1.%2").arg(j).arg(cnList.at(i)));
        j++;
    }
}

void softKey::on_spellEdit_textChanged(const QString &arg1)
{
    //qDebug()<<"change";
    this->cnList.clear();
    QString spelling=ui->spellEdit->text();

    //空拼音
    if(spelling.isEmpty())
    {
        for(int i=0;i<6;i++)
        {
            cnBT[i]->setText("");
        }
        return;
    }
    //qDebug()<<spelling;
    QString chinese=strList[spelling];
    if(chinese.isEmpty())
    {
        for(int i=0;i<6;i++)
        {
            cnBT[i]->setText("");
        }
        return ;
    }

    for(int i=0;i<chinese.size();i++)
    {
        cnList<<chinese.at(i);
    }
    //qDebug()<<chinese<<chinese.length()<<cnList.count();
    int j=1;
    int dev;
    for(int i=this->postion;i<postion+6&&i<cnList.count()-1;i++,j++)
    {
        cnBT[i]->setText(QString("%1.%2").arg(j).arg(cnList.at(i)));
        dev=6-j;
    }

    for(int i=0;i<dev;i++)
    {
        cnBT[i+dev]->setText("");
    }

}

void softKey::which_cn()
{
    QPushButton *button= (QPushButton*)sender();
    QString str=button->text();

    str.remove(0,2);
    ui->spellEdit->clear();
    emit send_cn(str);
}
